package com.msb.datastructure;

import java.util.PriorityQueue;

/**
 * 堆排序
 *
 * @author dataexa
 * @Date 2023/12/1
 */
public class HeapSortTest {

    public static void main(String[] args) {
        int[] arr = CommonUtils.randomIntArray(10, 20);
        heapSort(arr);
        CommonUtils.printArray(arr);
    }

    public static void heapSort(int[] arr) {
        // 先构建最大堆
//        for (int i = 0; i < arr.length; i++) {
//            heapInsert(arr, i);
//        }
        // 优化
        for (int i = arr.length - 1; i >= 0; i--) {
            heapFy(arr, i, arr.length);
        }
        int heapSize = arr.length;
        // 交换堆顶和最后一个元素
        CommonUtils.swap(arr, 0, --heapSize);
        while (heapSize > 0) {
            heapFy(arr, 0, heapSize);
            CommonUtils.swap(arr, 0, --heapSize);
        }
    }

    public static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[(index - 1) / 2]) {
            CommonUtils.swap(arr, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void heapFy(int[] arr, int index, int heapSize) {
        int left = 2 * index + 1;
        while (left < heapSize) {
            // 先找到子节点的最大值下标
            int largest = (left + 1 < heapSize) && (arr[left + 1] > arr[left]) ? left + 1 : left;
            // 子节点的最大值下标和父节点比较
            largest = arr[largest] > arr[index] ? largest : index;
            if (index == largest) {
                break;
            }
            CommonUtils.swap(arr, index, largest);
            index = largest;
            left = 2 * index + 1;
        }
    }
}
